﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SECSendMsgService
{
    /// <summary>
    /// 安全类负责加密和解密
    /// </summary>
    public class MySecurity
    {
        /// <summary>
        /// 加解密key
        /// </summary>
        private string key;
        public MySecurity(string key)
        {
            this.key = key;
        }

        #region 加密处理
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="stringToDecrypt"></param>
        /// <returns></returns>
        public  string DecryptString(string stringToDecrypt)
        {
            if (String.IsNullOrEmpty(stringToDecrypt))
            {
                return "";
            }

            string stringDecrypted = string.Empty;
            byte[] bytIn = Convert.FromBase64String(stringToDecrypt.Replace(" ", "+"));
            MemoryStream decryptStream = new MemoryStream();
            CryptoStream encStream = new CryptoStream(decryptStream, GenerateDESCryptoServiceProvider().CreateDecryptor(), CryptoStreamMode.Write);

            try
            {
                encStream.Write(bytIn, 0, bytIn.Length);
                encStream.FlushFinalBlock();
                stringDecrypted = Encoding.Default.GetString(decryptStream.ToArray());
            }
            catch
            {
                return "";
            }
            finally
            {
                decryptStream.Close();
                encStream.Close();
            }

            return stringDecrypted;
        }

        private  DESCryptoServiceProvider GenerateDESCryptoServiceProvider()
        {
            DESCryptoServiceProvider dCrypter = new DESCryptoServiceProvider();
            string Key =key;

            string sTemp;
            if (dCrypter.LegalKeySizes.Length > 0)
            {
                int moreSize = dCrypter.LegalKeySizes[0].MinSize;
                while (Key.Length > 7)
                {
                    Key = Key.Substring(0, 7);
                }
                sTemp = Key.PadRight(moreSize / 8, ' ');
            }
            else
            {
                sTemp = Key;
            }
            byte[] bytKey = ASCIIEncoding.ASCII.GetBytes(sTemp);

            dCrypter.Key = bytKey;
            dCrypter.IV = bytKey;

            return dCrypter;
        }
        #endregion
    }
}
